package com.zhongketech.sunflower.transport.uitl;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import com.zhongketech.sunflower.transport.Constant;
import com.zhongketech.sunflower.transport.InterfaceUrls;
import com.zhongketech.sunflower.transport.LogUtil;
import com.zhongketech.sunflower.transport.model.SmsCode;
import com.zhongketech.sunflower.transport.model.User;


import android.util.Base64;




public class NetTransportUtil {

	private static String TAG = "NetTransportUtil";
	public static final String BaseUrl = "http://182.92.193.118/sunflower/v1/index.php/";//待确认


	/**
	 * post提交数据
	 * 
	 * @param interfaceUrl
	 *            提交地址
	 * @param params
	 *            参数
	 * @param encoding
	 *            参数编码
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String getContentByPost(final String interfaceUrl,
			Map<String, String> params) {

		if(interfaceUrl == null){
			return null;
		}

		String url = BaseUrl + interfaceUrl;
		LogUtil.i(TAG, "request url= "+url);

		//添加body
		ByteArrayEntity entity = null;

		HttpClient httpClient = CustomerHttpClient.getHttpClient();

		if(null != params){

			/**
			 * 如果是注册，需在这里获取一下验证码
			 */
			if(InterfaceUrls.signUp.equals(interfaceUrl))
			{
				String phone = params.get("phone");
				String smsCodeUrl = BaseUrl+InterfaceUrls.smsCode+"?"+"phone="+phone;
				//LogUtil.i(TAG, "smsCodeUrl = "+smsCodeUrl);
				HttpGet httpGet = new HttpGet(smsCodeUrl);
				try {
					HttpResponse response = httpClient.execute(httpGet);
					Gson gson = new Gson();
					SmsCode smsCode = gson.fromJson(httpRequest(response), SmsCode.class);
					if(null != smsCode)
					{
						//LogUtil.i(TAG, "smsCode= "+smsCode.getSmscode());
						params.put("smscode", smsCode.getSmscode());
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			String requestBody = "{";
			Set set = params.entrySet();
			Iterator it = set.iterator();
			Map.Entry mapEntry = (Map.Entry) it.next();
			requestBody = requestBody+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			while (it.hasNext()) { // 遍历map中的每一项
				mapEntry = (Map.Entry) it.next();
				requestBody = requestBody+","+"\""+mapEntry.getKey()+"\""+":"+"\""+mapEntry.getValue()+"\"";
			}
			requestBody = requestBody+"}";
			LogUtil.i(TAG, "requestBody:"+requestBody);
			try {
				entity = new ByteArrayEntity(requestBody.getBytes("UTF-8"));
				entity.setContentType("application/json");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		if(null != entity) 
		{
			try {

				HttpPost request = new HttpPost(url);
				request.setEntity(entity);
				HttpResponse response = httpClient.execute(request);
				httpRequest(response);

			} catch (Exception e) {
				e.printStackTrace();
				LogUtil.i(TAG, "=============e="+e);
				LogUtil.d(TAG, "http error   " + interfaceUrl);
			}
		}

		return null;
	}

	private static String httpRequest(HttpResponse response)
	{
		try {
			LogUtil.i(TAG, "---------------------getStatusCode   ="+response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				//				String result = EntityUtils.toString(response.getEntity());
				byte[] resBytes = EntityUtils.toByteArray(response.getEntity());
				String result = new String(resBytes);
				LogUtil.i(TAG, "---------------  result= "+result);
				return result;
			}
			else if(response.getStatusLine().getStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR)
			{
				byte[] resBytes = EntityUtils.toByteArray(response.getEntity());
				String result = new String(resBytes);
				LogUtil.i(TAG, "---------------  result= "+Constant.decodeUnicode(result));
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			LogUtil.i(TAG, "=============e="+e);
		}

		return null;
	}
}